package com.itheima.train.manager.order.handler.controller;

import javax.websocket.OnClose;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import java.io.IOException;
import java.util.HashMap;

/**
 * @program: itheima-train-manager-parent
 * @description: 通知用户, 订单生成完成, 通过websocket`技术
 * @author: zhanghz001
 * @create: 2021-07-08 10:50
 **/
// @Component
// @ServerEndpoint(value = "/im/{userId}")
public class ZhzWebSocketServer {
    private static HashMap<String, Session> userIdSessionMap = new HashMap<>();
    private String userId;
    
    /**
     * 当前客户端和服务器建立连接了以后，在这里会执行该方法
     *
     * @param session
     * @param userId
     */
    @OnOpen
    public void open(@PathParam("userId") String userId, Session session) {
        
        //将当前用户id记录
        this.userId = userId;
        
        userIdSessionMap.put(userId, session);
    }
    
    @OnClose
    public void close() {
        userIdSessionMap.remove(userId);
    }
    
    //发送给用户
    public void sendMessageToUser(String userId, String message) {
        try {
            Session session = userIdSessionMap.get(userId);
            
            session.getBasicRemote().sendText(message);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
